﻿using liaowa2.Entity.DataModel;
using liaowa2.Entity.DTO;
using liaowa2.Utils;
using liaowa2.Utils.Cookie;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace liaowa2.Web.Controllers
{
    public class BaseController : Controller
    {
        public ManagerUser GetAdmin()
        {
            ManagerUser admin = new ManagerUser();
            if (Request.Cookies[ParameterConfig.CookieName] != null)
            {
                string EncryptData = Request.Cookies[ParameterConfig.CookieName].Value;
                admin = JsonConvert.DeserializeObject<ManagerUser>(EncodeSecurity.DecryptString(UtilsBase.UrlDecode(EncryptData)));
            }
            return admin;
        }

        public ManagerUser admin = new ManagerUser();
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (Request.Cookies["adminuser"] != null)
            {
                string EncryptData = Request.Cookies["adminuser"].Value;
                admin = JsonConvert.DeserializeObject<ManagerUser>(EncodeSecurity.DecryptString(UtilsBase.UrlDecode(EncryptData)));
                ViewBag.Admin = admin;
            }
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.IsChildAction)
                return;
            if (admin.user_name == null)
            {
                filterContext.Result = new RedirectResult("/login/index");
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        public static void LogoutBack()
        {
            CookieHelper.ClearCookie(ParameterConfig.CookieName);
        }

        public static ContentResult AlertByUrl(string message, string url)
        {
            ContentResult cr = new ContentResult();
            cr.Content = string.Format("<script>alert('{0}');</script><script>{1}</script>", message, url == "back" ? "history.back(-1);" : "window.location.href='" + url + "'");
            return cr;
        }

        public static void AlertMessage(string message)
        {
            string msgbox = "alert('" + message + "');window.history.back(-1)";
            System.Web.HttpContext.Current.Response.Write("<script type=\"text/javascript\">" + msgbox + "</script>");
            System.Web.HttpContext.Current.Response.End();
        }
    }
}